package com.epalmpay.service.message.impl;

import com.epalmpay.dto.messsage.*;
import com.epalmpay.dto.system.UserInDTO;
import com.epalmpay.dto.system.UserOutDTO;
import com.epalmpay.entity.DevicePos;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.SysMessageBase;
import com.epalmpay.entity.Userbase;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.device.IDeviceService;
import com.epalmpay.service.management.IMenuService;
import com.epalmpay.service.message.IMessageService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lifayi on 2017/5/9.
 */
@Service
public class MesssageServiceImpl implements IMessageService {

    @Autowired
    private SysMessageBaseMapper sysMessageBaseMapper;

    @Autowired
    private SysMessageInfoMapper sysMessageInfoMapper;

    @Autowired
    private UserbaseMapper userbaseMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private DevicePosRepairMapper devicePosRepairMapper;

    @Autowired
    private DevicePosMapper devicePosMapper;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private ShopMapper shopMapper;



    public List<SysMessageBase> listSysMessage(SysMessageQueryDTO sysMessageQueryDTO, Page page) throws ParseException {
        int messageType = sysMessageQueryDTO.getMessageType();

        SysMessageBase sysMessageBase = new SysMessageBase();
        sysMessageBase.setSendUserId(sysMessageQueryDTO.getSendUserId());
        sysMessageBase.setReceviceUserId(sysMessageQueryDTO.getReceviceUserId());
        sysMessageBase.setPage(page);
        sysMessageBase.setSendFrom(sysMessageQueryDTO.getSendFrom());
        sysMessageBase.setMessageType((byte) messageType);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String dateStart = sysMessageQueryDTO.getDateStart();
        String dateEnd = sysMessageQueryDTO.getDateEnd();

        if(!Tools.isEmpty(dateStart)) {
            Date dateStartDate = dateFormat.parse(dateStart);
            sysMessageBase.setDateStart(dateStartDate);
        }

        if(!Tools.isEmpty(dateEnd)) {
            Date dateEndDate = dateFormat.parse(dateEnd);
            sysMessageBase.setDateEnd(DateUtil.getDateNext(dateEndDate, 1));
        }


        if(sysMessageBase.getReceviceUserId() == null) {
            if(messageType == BizEnum.MessageType.System.getType()) {
                return sysMessageBaseMapper.sysMessagelistPage(sysMessageBase);
            } else {
                sysMessageBase.setGroupId(sysMessageQueryDTO.getGroupId());
                return sysMessageBaseMapper.sysMessagelistPage2(sysMessageBase);
            }
        } else {
            return sysMessageBaseMapper.sysMessageMerchantlistPage(sysMessageBase);
        }
    }

    public int addSysMessage(SysMessageInDTO sysMessageInDTO) throws Exception {
        Date date = new Date();

        SysMessageBase sysMessageBase = new SysMessageBase();
        sysMessageInDTO.setGmtCreate(date);
        PropertyCopyUtil.copyProperties(sysMessageInDTO, sysMessageBase);
        sysMessageBase.setSendUserId(sysMessageInDTO.getSendUserIds().get(0));
        sysMessageBase.setSendStatus((byte)0);  //默认发送失败
        sysMessageBaseMapper.insert(sysMessageBase);

        List<Userbase> userbaseList = new ArrayList<Userbase>();

        if(sysMessageInDTO.getMessageType() == (byte) BizEnum.MessageType.System.getType()) {   //如果是系统消息

            //获取要发给的大商户的所有操作员
            userbaseList.addAll(userbaseMapper.listUserIdByGroupIdAndUserType2(sysMessageInDTO.getSendUserIds(), CommonEnum.UserType.BusinessOperator.getType()));

            //移除无权限读取系统消息的操作员
//            for(int i = 0; i < userbaseList.size(); i++) {
//                long userId = userbaseList.get(i).getId();
//                if(!menuService.MenuRights(userId, 78)) {   //78表示系统消息，这里是从数据库直接拿来的
//                    userbaseList.remove(i);
//                }
//            }

            //加上管理员
            userbaseList.addAll(userbaseMapper.listUserIdByGroupIdAndUserType2(sysMessageInDTO.getSendUserIds(), CommonEnum.UserType.BusinessManager.getType()));

        } else {    //如果是站内信
            List<Long> agentIds = sysMessageInDTO.getAgentIds();
            if(agentIds != null && agentIds.size() > 0) {
                userbaseList.addAll(agentMapper.getUserBaseByAgentId2(agentIds));
            }

            List<Long> shopIds = sysMessageInDTO.getShopIds();
            if(shopIds != null && shopIds.size() > 0) {
                userbaseList.addAll(shopMapper.getUserBaseByShopId2(shopIds));
            }
        }

        int i = sysMessageInfoMapper.insertBatch(sysMessageBase.getId(), date, userbaseList);

        sysMessageBase.setSendStatus((byte)1);  //发送成功
        return sysMessageBaseMapper.updateByPrimaryKey(sysMessageBase);
    }

    @Transactional
    public void delSysMessage(SysMessageQueryDTO sysMessageQueryDTO) {
        List<Long> delItems = sysMessageQueryDTO.getDelItems();
        Long userId = sysMessageQueryDTO.getUserId();
        Integer userType = sysMessageQueryDTO.getUserType();

        if(sysMessageQueryDTO.getReceviceUserId() == null) {    //发送者端删除
            int messageType = sysMessageQueryDTO.getMessageType();
            if(delItems.get(0) == -1) {                         //删除所有消息
                if(userType == CommonEnum.UserType.ZfWorker.getType()) {   //掌富管理员删除
                    List<Long> ids = sysMessageBaseMapper.getIdByMessageTypeAndSendFrom((byte)messageType, null);
                    if(ids.size() > 0) {
                        sysMessageBaseMapper.deleteAllByMessageTypeAndSendFrom((byte)messageType, null);
                        sysMessageInfoMapper.deleteByMessageIds(ids);
                    }
                } else if(userType == CommonEnum.UserType.ZfOperator.getType()) {   //掌富操作员删除
                    List<Long> ids = sysMessageBaseMapper.getIdByMessageTypeAndSendFrom((byte)messageType, userId);
                    if(ids.size() > 0) {
                        sysMessageBaseMapper.deleteAllByMessageTypeAndSendFrom((byte)messageType, userId);
                        sysMessageInfoMapper.deleteByMessageIds(ids);
                    }
                } else if(userType == CommonEnum.UserType.BusinessManager.getType()) {  //大商户管理删除
                    List<Long> ids = sysMessageBaseMapper.getSysMessageIdsByGroupAdmin(userId);
                    if(ids.size() > 0) {
                        sysMessageBaseMapper.deleteByIds(ids);
                        sysMessageInfoMapper.deleteByMessageIds(ids);
                    }
                } else {                                                                //大商户操作员删除
                    List<Long> ids = sysMessageBaseMapper.getIdByMessageTypeAndSendFrom((byte)messageType, userId);
                    if(ids.size() > 0) {
                        sysMessageBaseMapper.deleteAllByMessageTypeAndSendFrom((byte)messageType, userId);
                        sysMessageInfoMapper.deleteByMessageIds(ids);
                    }
                }
            } else {                                            //根据消息ID列表删除
                if(userType == CommonEnum.UserType.ZfWorker.getType() || userType == CommonEnum.UserType.BusinessManager.getType()) {                //管理员删除
                    sysMessageBaseMapper.deleteByIdsAndSendFrom(delItems, null);
                    sysMessageInfoMapper.deleteByMessageIds(delItems);
                } else if(userType == CommonEnum.UserType.ZfOperator.getType() || userType == CommonEnum.UserType.BusinessOperator.getType()) {       //操作员删除
                    sysMessageBaseMapper.deleteByIdsAndSendFrom(delItems, userId);
                    sysMessageInfoMapper.deleteByMessageIds(delItems);
                }
            }
        } else {                                                //接收者端删除
            if(delItems.get(0) == -1) {
                sysMessageInfoMapper.deleteAllByOperator(sysMessageQueryDTO.getReceviceUserId());
            } else {
                sysMessageInfoMapper.deleteByMessageIdAndReceiver(delItems, sysMessageQueryDTO.getReceviceUserId());
            }
        }

    }

    public SysMessageOutDTO sysMessageDetail(Long id) throws Exception {
        SysMessageOutDTO sysMessageOutDTO = new SysMessageOutDTO();
        SysMessageBase sysMessageBase = sysMessageBaseMapper.getMemoById(id);
        PropertyCopyUtil.copyProperties(sysMessageBase, sysMessageOutDTO);
        return sysMessageOutDTO;
    }

    public SysMessageOutDTO sysMessageMerchantDetail(Long id) throws Exception {
        SysMessageOutDTO sysMessageOutDTO = new SysMessageOutDTO();
        SysMessageBase sysMessageBase = sysMessageBaseMapper.getMemoByMessageInfoId(id);
        PropertyCopyUtil.copyProperties(sysMessageBase, sysMessageOutDTO);
        sysMessageInfoMapper.updateHasReadByPrimaryKey(id, 1);  //1表示已读
        return sysMessageOutDTO;
    }


    @Override
    public List<TerminalMessageOutDTO> listTerminalMessage(TerminalMessageInDTO terminalMessageInDTO, Page page) throws Exception {

        Map<String,Object> param=new HashMap<String,Object>();

        param.put("sysId", terminalMessageInDTO.getSysId());
        param.put("sendFrom", terminalMessageInDTO.getSendFrom());
        param.put("sendFromId", terminalMessageInDTO.getSendFromId());
        param.put("repairStatus", terminalMessageInDTO.getRepairStatus());
        param.put("posTerminalSn", terminalMessageInDTO.getPosTerminalSn());
        param.put("joinStart", DateUtil.fomatDate(terminalMessageInDTO.getJoinStart()));
        param.put("joinEnd", DateUtil.fomatDate(terminalMessageInDTO.getJoinEnd()));
        param.put("messageType", terminalMessageInDTO.getMessageType());
        param.put("userId", terminalMessageInDTO.getUserId());
        param.put("groupId", terminalMessageInDTO.getGroupId());
        param.put("shopId", terminalMessageInDTO.getShopId());
        param.put("agentId", terminalMessageInDTO.getAgentId());

        List<TerminalMessageOutDTO> result = new ArrayList<TerminalMessageOutDTO>();

        int sumCount = sysMessageBaseMapper.selectMessageTerminalListCount(param);
        page.setTotalResult(sumCount);
        if(sumCount<=0)
            return null;

        param.put("limit", page.getShowCount());
        param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

        List<Map<String, Object>> resultList = sysMessageBaseMapper.sysMessageTerminalList(param);
        for (Map<String, Object> item : resultList) {
            TerminalMessageOutDTO messageOutDTO = new TerminalMessageOutDTO();
            messageOutDTO.setSysId((Long) item.get("id"));
            messageOutDTO.setDprId((Long) item.get("pos_repair_id"));
            messageOutDTO.setSendFrom((String) item.get("send_from_name"));
            messageOutDTO.setGmtCreate((Date) item.get("gmt_create"));
            messageOutDTO.setMessageType(BizEnum.MessageType.POSRepair.getType());
            messageOutDTO.setPosTerminalSn((String) item.get("pos_terminal_sn"));
            messageOutDTO.setRepairStatus((Integer) item.get("repair_status"));
            messageOutDTO.setShopName((String) item.get("merchant_name"));
            messageOutDTO.setDeviceName((String) item.get("device_name"));
            result.add(messageOutDTO);
        }

        return result;
    }


    @Override
    public List<SysMessageBase> getSysMessageList(SysMessageInDTO sysMessageInDTO) throws Exception {
//        return sysMessageBaseMapper.getSysMessageList(sysMessageInDTO.getMessageType(), sysMessageInDTO.getGroupId(), sysMessageInDTO.getShopId(), sysMessageInDTO.getAgentId());
        return null;
    }

    @Override
    public TerminalMessageOutDTO getTerminalMessageDetail(TerminalMessageInDTO terminalMessageInDTO) throws Exception {

        TerminalMessageOutDTO terminalMessageOutDTO = new TerminalMessageOutDTO();

        Map<String,Object> param=new HashMap<String,Object>();

        Map<String, Object> result = null;

        if (terminalMessageInDTO.getSysId() != null) {
            param.put("sysId", terminalMessageInDTO.getSysId());
            param.put("messageType", terminalMessageInDTO.getMessageType());
            result = sysMessageBaseMapper.sysMessageTerminalDetail(param);
        }

        if (terminalMessageInDTO.getPosId() != null){
            result = devicePosMapper.getDevicePosByPosId(terminalMessageInDTO.getPosId());
        }


        if (result != null){
            terminalMessageOutDTO.setShopId((Long) result.get("shop_id"));
            terminalMessageOutDTO.setAgentId((Long) result.get("agent_id"));
            terminalMessageOutDTO.setGroupId((Long) result.get("group_id"));
            terminalMessageOutDTO.setDeviceName((String) result.get("device_name"));
            terminalMessageOutDTO.setShopName((String) result.get("shopName"));
            terminalMessageOutDTO.setAgentName((String) result.get("agentName"));
            terminalMessageOutDTO.setRepairStatus((Integer) result.get("repair_status"));
            terminalMessageOutDTO.setPosTerminalSn((String) result.get("pos_terminal_sn"));
            terminalMessageOutDTO.setContackPhone((String) result.get("contack_phone"));
            terminalMessageOutDTO.setContact((String) result.get("contact"));
            terminalMessageOutDTO.setUsedAddress((String) result.get("used_address"));
            terminalMessageOutDTO.setProblemDesc((String) result.get("problem_desc"));
            terminalMessageOutDTO.setGmtCreate((Date) result.get("gmt_create"));
            terminalMessageOutDTO.setDprId((Long) result.get("dprId"));
            terminalMessageOutDTO.setPosId((Long) result.get("posId"));
            terminalMessageOutDTO.setPosStatus((Integer) result.get("pos_status"));

            //根据原始posId查找新POS序列号
            if (result.get("posId") != null){
                DevicePos devicePos = new DevicePos();
                devicePos = devicePosMapper.selectByReplacePosId((Long) result.get("posId"));
                if (devicePos != null) {
                    terminalMessageOutDTO.setNewPosTerminalSn(devicePos.getPosTerminalSn());
                }
            }
        }






        return terminalMessageOutDTO;
    }

    @Override
    public int updatePosRepairStatus(TerminalMessageInDTO terminalMessageInDTO) {
        return deviceService.updateDevicePosRepairStatus(terminalMessageInDTO.getPosId(),terminalMessageInDTO.getDprId(), terminalMessageInDTO.getRepairStatus());
    }

    @Override
    public TerminalMessageOutDTO getOldPosInfo(TerminalMessageInDTO terminalMessageInDTO) throws Exception {

        TerminalMessageOutDTO terminalMessageOutDTO = new TerminalMessageOutDTO();

        Map<String, Object> result = devicePosRepairMapper.getDevicePosInfoByPosRepairId(terminalMessageInDTO.getDprId());

        if (result != null){

            terminalMessageOutDTO.setShopName((String) result.get("shopName"));
            terminalMessageOutDTO.setAgentName((String) result.get("agentName"));
            terminalMessageOutDTO.setGroupName((String) result.get("groupName"));
            terminalMessageOutDTO.setPosId((Long) result.get("pos_id"));
            terminalMessageOutDTO.setPosTerminalSn((String) result.get("pos_terminal_sn"));
            terminalMessageOutDTO.setPosOrganization((Integer) result.get("pos_organization"));
            terminalMessageOutDTO.setPosMerchantId((String) result.get("pos_merchant_id"));
            terminalMessageOutDTO.setShopTerminalSn((String) result.get("shop_terminal_sn"));
            terminalMessageOutDTO.setAuthorizedCode((String) result.get("authorized_code"));
            terminalMessageOutDTO.setNetFeeRate((Integer) result.get("net_fee_rate"));
            terminalMessageOutDTO.setNetMerchantName((String) result.get("net_merchant_name"));
            terminalMessageOutDTO.setDeviceId((Long) result.get("device_id"));
            terminalMessageOutDTO.setDeviceStatus((Integer) result.get("device_status"));
        }

        return terminalMessageOutDTO;
    }

    @Override
    public Map<String, List<String>> viewReceiver(Long id) {
        Map<String, List<String>> siteMessageReceiverInfo = new HashMap<>();
        List<String> shopNameList = sysMessageInfoMapper.viewReceiverShop(id);
        siteMessageReceiverInfo.put("shopNameList", shopNameList);
        List<String> agentNameList = sysMessageInfoMapper.viewReceiverAgent(id);
        siteMessageReceiverInfo.put("agentNameList", agentNameList);
        return siteMessageReceiverInfo;
    }

    @Override
    public UserOutDTO getuserId(UserInDTO userInDTO) throws Exception {
        return userbaseMapper.getuserId(userInDTO);
    }
}
